/**
 * All Rights Reserved , Copyright (C) 2022 , 青岛鼎信通讯股份有限公司
 *
 *MpmProjectUnBidScoreController
 * 评标细则不创建申请表
 *
 * 修改纪录
 * 2022-05-24 版本：1.0 hudeyong 创建。
 * @version 版本：1.0
 * @author 作者：hudeyong
 * 创建日期：2022-05-24
 */

package com.topscomm.mpm.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollectionUtil;
import com.topscomm.basic.exception.MessageException;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.mpm.pojo.MpmProjectEntity;
import com.topscomm.mpm.service.impl.MpmProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboApprovalFlowInsEntity;
import com.topscomm.cbo.service.ICboApprovalFlowInsService;
import com.topscomm.mpm.controller.auto.MpmProjectUnBidScoreControllerAuto;
import com.topscomm.mpm.pojo.MpmProjectUnBidScoreEntity;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.common.SessionUserBean;
import com.topscomm.tap.common.TapSystemConst.TapOperationTypeEnum;

/**
 * @author: hudeyong
 * @date: 2022-05-24
 * @description:评标细则不创建申请表Controller
 * @modify:
 */
@RestController
@RequestMapping("mpm/projectUnBidScore")
public class MpmProjectUnBidScoreController extends MpmProjectUnBidScoreControllerAuto implements IMpmProjectUnBidScoreController {
	@Autowired
	private MpmProjectService mpmProjectService;
	/**
	 * @author: hudeyong
	 * @date: 2022-05-24
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" enabled=1 ");
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and state={0}", value);
		}
		if (paraMap.containsKey("qry_docno")) {
			String value = paraMap.get("qry_docno").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docno like '%{0}%'", value);
		}
		if (paraMap.containsKey("qry_begindocdate")) {
			String value = paraMap.get("qry_begindocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_enddocdate")) {
			String value = paraMap.get("qry_enddocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		if (paraMap.containsKey("qry_deptname")) {
			String value = paraMap.get("qry_deptname").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (deptid in ( SELECT id from CboDept where fullname like '%{0}%'))", value);
		}
		if (paraMap.containsKey("qry_username")) {
			String value = paraMap.get("qry_username").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (username like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_deptcode")) {
			String value = paraMap.get("qry_deptcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and deptcode like '{0}%'", value);
		}
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and state={0}", value);
		}
		if (paraMap.containsKey("qry_where")) {
			String value = paraMap.get("qry_where").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and {0}", value);
		}
		if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
		{
			String dataPession = service.getDataPermission(TapOperationTypeEnum.Select, "", this.getUserBean());
			if (StringUtil.isEmpty(dataPession))// 默认权限只能看本人，部门负责人为自己的部门和下级部门的数据
			{
				String deptcodes_header = ConvertUtil.convertToString(this.getUserBean().getUser().getValue("deptcodes_header"));
				if (StringUtil.isEmpty(deptcodes_header))
					sql.appendSingle(" and (usercode = '{0}' or deptcode ='{1}' or deptcode = '{2}' )", this.getUserBean().getUser().getCode(), this.getUserBean().getDept().getCode(), this
							.getUserBean().getWorkDept().getCode());
				else
					sql.appendSingle(" and (deptcode in ({0})  or usercode = '{1}' or deptcode ='{2}' or deptcode = '{3}' )", deptcodes_header, this.getUserBean().getUser().getCode(), this
							.getUserBean().getDept().getCode(), this.getUserBean().getWorkDept().getCode());
			} else// 使用数据权限
			{
				sql.appendSingle(" and {0} ", dataPession);
			}
		}
		return sql.toString();
	}

	/**
	 * @author: hudeyong
	 * @date: 2022-05-24
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/**
	 *
	 * @description: 提交审批前
	 * @param dataMap
	 * @param paraMap
	 * @throws Exception
	 * @author: hudeyong
	 * @date: 2022-05-24
	 * @modify:
	 */
	@Override
	protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
		super.beforeSubmit(dataMap, paraMap);
		StringBufferProxy mailtitle = new StringBufferProxy();
		mailtitle.appendSingle("{0}{1}于{2}提交评标细则不创建申请表申请,单据编号{3}! ", dataMap.get("dispdeptcode"), dataMap.get("username"), DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
		dataMap.put("maintitle", mailtitle.toString());
	}

	/**
	 * @author: hdy
	 * @date: 2022-04-26
	 * @param paraMap
	 * @return
	 * @description:提交无评分细则审批
	 * @modify:
	 */
	@PutMapping(value = "/submitUnBidScore")
    public ResponseResult<Object> submitUnBidScore(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			StringBufferProxy sql = new StringBufferProxy();
			String projectcode = ConvertUtil.convertToString(paraMap.get("projectcode"));
			String projectname = ConvertUtil.convertToString(paraMap.get("projectname"));
			String times = ConvertUtil.convertToString(paraMap.get("times"));
			long returnid = 0L;
			sql.appendSingle("select * from MpmProjectUnBidScore where PROJECTCODE  = '{0}' and bidscoretimes = '{1}' ",projectcode, times);
			List<Map<String, Object>> unBidScoreLists = this.service.selectExecute(sql.toString());
			// 如果存在历史单据（开立、退回），对历史单据进行提交，否则新增单据
			if(unBidScoreLists.size()>0) {
				unBidScoreLists.get(0).put("docdate", new Date());
				this.submit(unBidScoreLists.get(0));
				returnid = ConvertUtil.convertToLong(unBidScoreLists.get(0).get("id"));
			} else {
				List<Map<String, Object>> flowidList = flowDatacodeCache.getApprovalFlowListMap("ApprovalFlow_MpmProjectUnBidScore", this.getUserBean(), "sortcode");
				MpmProjectUnBidScoreEntity unBidScoreEntity = new MpmProjectUnBidScoreEntity();
				unBidScoreEntity.setProjectcode(projectcode);
				unBidScoreEntity.setProjectname(projectname);
				unBidScoreEntity.setDeptname(ConvertUtil.convertToString(getUserBean().getDept().getFullname()));
				unBidScoreEntity.setDeptcode(ConvertUtil.convertToString(getUserBean().getDept().getCode()));
				unBidScoreEntity.setUsername(ConvertUtil.convertToString(getUserBean().getUser().getName()));
				unBidScoreEntity.setUsercode(ConvertUtil.convertToString(getUserBean().getUser().getCode()));
				unBidScoreEntity.setFlowid(ConvertUtil.convertToLong(flowidList.get(0).get("id")));
				unBidScoreEntity.setBidscoretimes(times);
				unBidScoreEntity.setDocdate(new Date());
				this.submit(unBidScoreEntity.convertToMap());
				// 获取新增id
				sql.clear();
				sql.appendSingle("select id from MpmProjectUnBidScore where PROJECTCODE  = '{0}' and bidscoretimes = '{1}' ",projectcode, times);
				returnid = ConvertUtil.convertToLong(this.service.selectExecute(sql.toString()).get(0).get("id"));
			}
			sql.clear();
			// 修改主表无评分细则审批状态
			sql.appendSingle("UPDATE MPMPROJECT SET EXISTBIDSCORESTATE = '1' WHERE PROJECTCODE = '{0}'", projectcode);
			this.service.updateExecute(sql.toString());
			// 返回审批表id
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("existbidscoreid", returnid);
			return ResponseResult.ok(resultMap);
		} catch (Exception ex) {
			return this.handleControllerException(ex);
		}
	}
	/**
	 * @author: houyuhang
	 * @date: 2023-06-03
	 * @param paraMap
	 * @return
	 * @description:不填写评分细则对应项目
	 * @modify:
	 */
	@GetMapping(value = "/unbidProject")
	public ResponseResult<Object> unbidProject(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			String id = ConvertUtil.convertToString(paraMap.get("id"));
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle(" projectcode in (select projectcode from mpmprojectunbidscore where id = '{0}') ", id);
			List<MpmProjectEntity> mpmProjectEntities = mpmProjectService.queryByWhere(sql.toString());
			if (CollectionUtil.isEmpty(mpmProjectEntities)) {
				throw new MessageException("未找到对应项目，请联系管理员！");
			}
			return ResponseResult.ok(mpmProjectEntities.get(0));
		} catch (Exception ex) {
			return this.handleControllerException(ex);
		}
	}
}

